from django.shortcuts import render, HttpResponse
from user_system import models
from utils.auth_manog import auth_manog_done
from utils.hashlib_done import encryption
from django.http import JsonResponse
from k8sMp.settings import theme_dict
from k8sMp.settings import logger
from utils.get_access_ip import get_access_ipaddress

# Create your views here.

def login(request):
    # access_ip = get_access_ipaddress(request)
    # request_path = request.path
    # logger.info("%s 访问 %s"%(access_ip,request_path))
    if request.method == "GET":

        ##########################是否有初始账号##########################
        # 创建初始账号密码
        name = "super_root"
        password = "super_boamp"
        password = encryption(password)  # 加密密码
        if not models.User.objects.filter(name=name).first():
            models.UserType.objects.create(id=1, name="超级管理员")
            models.UserType.objects.create(id=2, name="管理员")
            models.UserType.objects.create(id=3, name="普通用户")
            models.User.objects.create(name=name, password=password, usertype_id=1)
        if not models.MyAuthType.objects.all():
            models.MyAuthType.objects.create(auth_type="key")
            models.MyAuthType.objects.create(auth_type="password")
        ##########################是否有初始账号##########################

        request.session.set_expiry(0.1) #当访问登陆页面时，使当前的session失效，避免无验证也能根据历史session成功登陆
        request.session.clear_expired() #将所有Session失效日期小于当前日期的数据删除
        return render(request, "super_cmdb/login.html")
    elif request.method == "POST":
        access_ip = get_access_ipaddress(request)
        username = request.POST.get("username")
        password = request.POST.get("password")
        password = encryption(password) #加密密码
        user_info = models.User.objects.filter(name=username,password=password).first()
        if user_info:
            #print(username,password)
            request.session["user_id"] = user_info.id
            request.session["username"] = username
            request.session["is_login"] = True
            request.session.set_expiry(7200)   #设置session有效期
            logger.info("%s login Success"%username)
            login_info = "IP: %s ，登陆平台成功"%access_ip
            models.OpsLogger.objects.create(log_user=username,log_ops=login_info)
            #return redirect("/super_cmdb/index")
            return HttpResponse("ok")
        else:
            #return render(request, "super_cmdb/login.html")
            status = {"code":1,"msg":"登陆失败,请检查账号密码"}
            logger.info("%s login Failed" % username)
            login_info = "IP: %s ，登陆平台失败，验证用户密码错误" % access_ip
            models.OpsLogger.objects.create(log_user=username, log_ops=login_info)
            return JsonResponse(status)

@auth_manog_done
def welcome(request):
    user_id = request.session.get("user_id")
    # username = request.session.get("username")
    # access_ip = get_access_ipaddress(request)
    # request_path = request.path
    # logger.info("%s %s 访问 %s" % (access_ip, username, request_path))
    user_list = models.User.objects.all()
    # host_list = models.ServerHost.objects.all()
    # tasks_number = models.TaskList.objects.all().count()
    # domain_number = models.DomainList.objects.all().count()
    project_number = models.Project.objects.all().count() - 1
    dev_record_list = models.DevRecord.objects.all().order_by("-id")[:10]
    # gameserver_number = models.GameServer.objects.all().count()
    # cleint_update_number = models.ClientResourcesOps.objects.all().count()
    if user_id == 22:
        url = "super_cmdb/welcome_waibu.html"
    else:
        url = "super_cmdb/welcome.html"

    return render(request, url, {
        "user_list": user_list,
        # "host_list": host_list,
        # "tasks_number": tasks_number,
        # "domain_number": domain_number,
        "project_number": project_number,
        "dev_record_list": dev_record_list,
        # "gameserver_number": gameserver_number,
        # "cleint_update_number": cleint_update_number
    })

@auth_manog_done
def index(request):
    user_id = request.session.get("user_id")
    current_theme_obj = models.SelectTheme.objects.filter(user_id=user_id).first()
    if current_theme_obj:
        current_theme_number = current_theme_obj.theme_number
    else:
        current_theme_number = 0
    current_theme_name = theme_dict[current_theme_number]["name"]
    current_theme = [current_theme_number, current_theme_name]
    project_list = models.User.objects.filter(id=user_id).first().project.all().order_by("-name") # 获取用户拥有权限的项目
    select_project_name = "选择操作项目"
    select_project_info = models.SelectDefaultProject.objects.filter(b_user_id=user_id).first()
    user_obj = models.User.objects.get(id=user_id)
    usertype_id = user_obj.usertype_id
    if select_project_info:
        project_id = select_project_info.select_project_id
        request.session["project_id"] = project_id
        select_project_name = models.Project.objects.filter(id=project_id).first().name
    else:
        # 配置全局session，后面调用，project_id为主要中心,默认为None
        request.session["project_id"] = None
        project_id = None
    if request.method == "POST":
        # 如果获取不到就用历史记录的
        project_id = request.POST.get("project_id", project_id)
        theme_number = request.POST.get("theme_number", None)
        if theme_number:
            if not models.SelectTheme.objects.filter(user_id=user_id).first():
                models.SelectTheme.objects.create(theme_number=theme_number,user_id=user_id)
            else:
                models.SelectTheme.objects.filter(user_id=user_id).update(theme_number=theme_number)
        else:
            # 配置全局session，后面调用，project_id为主要中心
            request.session["project_id"] = project_id
            select_project_name = models.Project.objects.filter(id=project_id).first().name
        # 记录选中项目历史
        if select_project_info:
            select_info_obj = models.SelectDefaultProject.objects.get(b_user_id=user_id)
            select_info_obj.select_project_id = project_id
            select_info_obj.save()
        else:
            models.SelectDefaultProject.objects.create(b_user_id=user_id,select_project_id=project_id)
    if usertype_id >= 3:
        return render(request, 'super_cmdb/index_ordinary.html',{
            "project_list": project_list,
            "select_project_name": select_project_name,
            "current_theme": current_theme,
            "theme_dict": theme_dict
        })
    else:
        return render(request, 'super_cmdb/index.html', {
            "project_list": project_list,
            "select_project_name":select_project_name,
            "current_theme": current_theme,
            "theme_dict": theme_dict
        })

@auth_manog_done
def icon(request):
    return render(request, 'super_cmdb/unicode.html')

@auth_manog_done
def dev_record(request):
    if request.method == "GET":
        dev_record_list = models.DevRecord.objects.all().order_by("-create_time")
        return render(request, 'super_cmdb/dev_record.html',{"dev_record_list":dev_record_list})

@auth_manog_done
def dev_record_add(request):
    if request.method == "GET":
        return render(request, 'super_cmdb/dev_record_add.html')
    elif request.method == "POST":
        name = request.POST.get("name")
        content = request.POST.get("content")
        try:
            models.DevRecord.objects.create(name=name,content=content)
            return HttpResponse("ok")
        except Exception as e:
            print(e)
            return HttpResponse("not ok")
